package com.kkb.mybatis.framework.config;

import com.kkb.mybatis.framework.executor.CachingExecutor;
import com.kkb.mybatis.framework.executor.Executor;
import com.kkb.mybatis.framework.executor.SimpleExecutor;
import com.kkb.mybatis.framework.handler.*;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

public class Configuration {

    /**
     * 数据源
     */
    private DataSource dataSource;

    private Boolean useCache = true;

    /**
     * statement信息封装
     */
    private Map<String, MappedStatement> statementMap = new HashMap();

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public MappedStatement getMappedStatementById(String statementId) {
        return statementMap.get(statementId);
    }

    public void addMappedStatement(String statementId, MappedStatement mappedStatement) {
        this.statementMap.put(statementId, mappedStatement);
    }

    public Executor newExecutor(String executorType) {
        executorType = executorType == null || "".equals(executorType)?"simple":executorType;

        Executor executor = null;
        if ("simple".equals(executorType)) {
            executor = new SimpleExecutor();
        }

        if (useCache){
            executor = new CachingExecutor(executor);
        }

        return executor;
    }

    public StatementHandler getStatementHandler(String statementType) {
        statementType = statementType == null || "".equals(statementType)?"prepared":statementType;

        StatementHandler statementHandler = null;
        if ("prepared".equals(statementType)){
            statementHandler = new PreparedStatementHandler(this);
        }

        return statementHandler;
    }

    public ParameterHandler newParameterHandler() {
        return new DefaultParameterHandler();
    }

    public ResultSetHandler newResultSetHandler() {
        return new DefaultResultSetHandler();
    }
}
